<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.shopId" clearable :placeholder="$t('请选择门店')" class="filter-item">
        <el-option v-for="item in shops" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-input v-model="listQuery.merchandiseSn" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Merchandise_number')" />
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Product_name')" />
      <el-select v-model="listQuery.waning" clearable class="filter-item" :placeholder="$t('请选择库存状态')">
        <el-option :value="1" :label="$t('库存预警')" />
        <el-option :value="2" :label="$t('库存正常')" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('Search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-message" @click="handleUpdate" round>{{
        $t('设置预警提醒')
      }}</el-button>

<!--      <el-button v-shop="false" class="filter-item" plain icon="el-icon-upload" @click="importDialogVisible =true" >{{
          $t('导入门店原料')
        }}</el-button>-->
      <!--  <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{$t('Find')}}</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table ref="table" v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit
          :header-cell-style="{'background':	'#F5F5F5', 'color':'#000000'}"
      highlight-current-row>
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" :index="getIndex" width="50" :label="$t('序号')"></el-table-column>

      <el-table-column align="center" width="160" min-width="100" :label="$t('门店名称')" prop="shopName" />

      <el-table-column align="center" min-width="100" :label="$t('原料编号')" prop="merchandiseSn" />

      <el-table-column align="center" width="150"  min-width="100" :label="$t('原料名称')" prop="name" />

      <el-table-column align="center" :label="$t('Specifications')" prop="standard" />

     <!--  <el-table-column align="center" :label="$t('Model')" prop="model" /> -->
      <el-table-column align="center" width="120" :label="$t('原料图片')" prop="picUrl">
        <template slot-scope="scope">
          <el-image preview-src-list style="border-radius:15%;width:60px" :src="scope.row.picUrl"  lazy>
            <div slot="error" class="image-slot">
              <i style="font-size: 30px" class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('价格')" prop="sellPrice">
        <template slot-scope="scope">
          ${{scope.row.sellPrice}}
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" :label="$t('Stock') + '(' + $t('Product_basic_unit') + ')'" prop="basicUnit">
        <template slot-scope="scope">
          {{ scope.row.basicNumber + "(" + scope.row.basicUnit + ")" }}
        </template>
      </el-table-column>

      <el-table-column align="center" width="120" :label="$t('Stock') + '(' + $t('Product_check_unit') + ')'" prop="number">
        <template slot-scope="scope">
          <span v-if="scope.row.warnNumber && scope.row.number <= scope.row.warnNumber" style="color:#F56C6C">{{
            scope.row.number + "(" + scope.row.checkUnit + ")"
          }}</span>
          <span v-if="!scope.row.warnNumber || scope.row.number > scope.row.warnNumber">{{
            scope.row.number + "(" +
              scope.row.checkUnit + ")"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="120" :label="$t('Stock') + '(' + $t('Product_sub_unit') + ')'" prop="number">
        <template slot-scope="scope">
<!--          <span v-if="scope.row.number">{{
            Math.ceil(scope.row.number / scope.row.ratio) + "(" + scope.row.unit +
              ")"
          }}</span>-->
          <span v-if="scope.row.number">{{
            scope.row.stockNumber +"(" + scope.row.unit +
              ")"
            }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('预警下限')" prop="warnNumber"></el-table-column>
      <el-table-column align="center" width="120" :label="$t('盘点亏损值')" prop="lossValue"></el-table-column>
      <el-table-column align="center" :label="$t('预警状态')" prop="basicUnit">
        <template slot-scope="scope">
          <span v-if="scope.row.warnNumber && scope.row.number <= scope.row.warnNumber" style="color:#F56C6C">异常</span>
          <span v-if="!scope.row.warnNumber || scope.row.number > scope.row.warnNumber" style="color:#19aa21">正常</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('Operate')" align="center" width="160">
        <template slot-scope="scope">
          <!-- v-permission="['GET /admin/p/store_user_edit']" -->
          <el-button v-permission="['GET /admin/p/stock_storeproduct_setwarn']" size="mini" type="text"
            @click="openWarnNumberDialog(scope.row)">{{ $t('Set_warn_number') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog :visible.sync="setWarnNumerDialogVisible" :title="$t('Set_warn_number')">
      <el-form ref="setWarnNumerForm" :model="setWarnNumerForm" :rules="setWarnNumerFormRules" status-icon
        label-position="left" label-width="200px">
        <el-form-item :label="$t('Merchandise_number')" prop="merchandiseSn">
          {{ setWarnNumerForm.merchandiseSn }}
        </el-form-item>
        <el-form-item :label="$t('Product_name')" prop="name">
          {{ setWarnNumerForm.name }}
        </el-form-item>
        <el-form-item :label="$t('Warn_number')" prop="warnNumber">
          <el-input v-model.number="setWarnNumerForm.warnNumber"></el-input>
        </el-form-item>
        <el-form-item :label="$t('盘点亏损值')" prop="lossValue">
          <el-input v-model.number="setWarnNumerForm.lossValue"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setWarnNumerDialogVisible = false">{{ $t('Cancel') }}</el-button>
        <el-button @click="handleWarnNumber()" type="primary">{{ $t('Confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog width="28%" :title="$t('导入门店原料')" :visible.sync="importDialogVisible">
        <el-upload drag multiple accept=".xlsx,.xls"
           :headers="headers" :auto-upload="false"
           :file-list="fileList" ref="importUpload"
            :action="shopMerchandiseExcelPath + '?shopId=' + importShopMerchandise.shopId">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <p >仅允许导入 xls、xlsx 格式文件。 <el-link type="primary" @click="handleImportTemplate" :underline="false">下载模板</el-link></p>
          <el-select filterable v-model="importShopMerchandise.shopId" clearable :placeholder="$t('请选择门店')" class="filter-item">
            <el-option v-for="item in shops" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="importDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleImportUpload">确 定</el-button>
          </span>
    </el-dialog>

    <SetEarlyWarningReminders ref="SetEarlyWarningReminders" :dialogVisible="SetEarlyWarningRemindersDialogVisible"
      @SetEarlyWarningRemindersCancel="SetEarlyWarningRemindersCancel" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { materialList, materialApply, materialShopList, billnumber ,getImportTemplate} from '@/api/erp'
import { SetEarlyWarningReminders } from './components/index';
import { setShopMerchandiseNumber } from '@/api/merchandise'
import { MessageBox } from 'element-ui'
import { infoAdmin } from '../../api/admin'
import { getShopAll } from '@/api/shop'
import { getToken } from "@/utils/auth";
import {shopMerchandiseExcelPath} from '@/api/storage'


export default {
  name: 'merchandiseShopList',
  components: { Pagination, SetEarlyWarningReminders },
  data() {
    return {
      //导入门店原料
      shopMerchandiseExcelPath,
      fileList:[],
      importDialogVisible:false,
      importShopMerchandise:{
          shopId:undefined,
          fileList:[],
      },

      total: 0,
      listLoading: false,
      downloadLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        merchandiseSn: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      setWarnNumerDialogVisible: false,
      SetEarlyWarningRemindersDialogVisible: false,
      setWarnNumerForm: {
        shopId: undefined,
        id: undefined,
        merchandiseSn: undefined,
        name: undefined,
        warnNumber: 0,
        lossValue: 0,
      },
      setWarnNumerFormRules: {
        warnNumber: [
          { required: true, message: this.$t('Stock_amount_cannot_be_empty'), trigger: 'blur' },
          { type: 'number', message: this.$t('Stock_amount_must_be_a_number') }
        ]
      },
      list: [],
      shops: [],
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    if (this.$route.query.shopId) {
      this.listQuery.shopId = this.$route.query.shopId
    }

    if (this.listQuery.shopId == undefined) {
      infoAdmin().then(res => {
        this.listQuery.shopId = res.data.data.admin.shopId
      })
    }

    this.getList()
    getShopAll().then(res => {
      const response = res.data.data;
      this.shops = response;
    })
  },
  methods: {
    handleImportTemplate(){
      const url = "https://app.lumierecafe.com/mi/lumierecafe/app/%E5%8E%9F%E6%96%99%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
      const link = document.createElement("a");
      link.href = url;
      link.download = "原料导入模板.xlsx"; // 文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
     /*getImportTemplate().then((res) => {
       // 处理返回的文件流
       let blob = new Blob([res.data], { type: res.data.type });
       //获取fileName,截取content-disposition的filename；按=分割，取最后一个
       const fileName = decodeURI(res.headers['content-disposition'].split("=")[1], "UTF-8");
       let downloadElement = document.createElement("a");
       let href = window.URL.createObjectURL(blob); //创建下载的链接
       downloadElement.href = href;
       downloadElement.download = fileName; //下载后文件名
       document.body.appendChild(downloadElement);
       downloadElement.click(); //点击下载
       document.body.removeChild(downloadElement); //下载完成移除元素
       window.URL.revokeObjectURL(href); //释放blob
       this.$message.success("[图书信息]已成功导出!");
     })
         .catch(function(error) {
           // 请求失败处理
           console.log(error);
         });*/
    },
    handleImportUpload(){
        if(!this.importShopMerchandise.shopId){
          this.$notify.success({
            title: this.$t('Success!'),
            message: '请选择门店'
          })
          return;
        }
      this.$refs.importUpload.submit();
      this.$notify.success({
        title: this.$t('Success!'),
        message: '资料已提交上传'
      })
      this.importDialogVisible = false;
      this.fileList = [];
      this.importShopMerchandise.shopId = undefined;
    },
    handleUpdate() {
      // this.SetEarlyWarningRemindersDialogRow = row;
      this.$refs.SetEarlyWarningReminders.init()
      this.SetEarlyWarningRemindersDialogVisible = true;
    },
    SetEarlyWarningRemindersCancel() {
      this.SetEarlyWarningRemindersDialogVisible = false;
      // console.log(11);
    },
    getList() {
      materialShopList(this.listQuery).then(res => {
        this.list = res.data.data.list
        this.total = res.data.data.total
      }).catch(() => {
        this.list = []
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getList()
    },
    openWarnNumberDialog(row) {
      this.setWarnNumerForm.shopId = row.shopId
      this.setWarnNumerForm.id = row.id
      this.setWarnNumerForm.merchandiseSn = row.merchandiseSn
      this.setWarnNumerForm.name = row.name
      this.setWarnNumerForm.warnNumber = row.warnNumber
      this.setWarnNumerForm.lossValue = row.lossValue
      this.setWarnNumerDialogVisible = true
    },
    handleWarnNumber() {
      this.$refs['setWarnNumerForm'].validate(valid => {
        if (valid) {
          setShopMerchandiseNumber(this.setWarnNumerForm).then(response => {
            this.$notify.success({
              title: this.$t('Success!'),
              message: '修改成功'
            })
            this.setWarnNumerDialogVisible = false
            this.getList()
          })
            .catch(response => {
              MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
                confirmButtonText: this.$t('Confirm'),
                type: 'error'
              })
            })
        }
      })
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    },
  }
}
</script>

<style scoped>

</style>
